from utils.mail_util import send_registry_mail, send_reset_mail
from utils.sql_utils.set import user_data, code_data, database, cursor
from utils.str_util import gen_random_str, get_timestamp


def registry_user(email: str, icode: str) -> int:
    """
    注册用户
    :param icode: 邀请码
    :param email: 邮箱
    :return: 0:注册成功,1:邮箱已被注册,2:邀请码已失效,3服务器异常
    """
    if not email_check(email):
        return 1

    if not icode_check(icode):
        return 2

    password = gen_random_str(8)
    uname = "用户"
    level = 2
    headurl = "lumine.jpg"

    if icode == 'Z3F47NAT2ZZ35RHD':
        level = 0

    try:
        use_icode(icode)
        cursor.execute(f'insert into {user_data} (uemail, uname, password, level, headurl)'
                       f' values("{email}", "{uname}", "{password}", "{level}", "{headurl}")')
        database.commit()
    except Exception as e:
        print(e)
        return 3

    send_registry_mail(receiver=email, password=password)

    return 0


def reset_user_password(email: str) -> int:
    """
    重置用户密码
    :param email: 用户邮箱
    :return: 0:重置成功,1:邮箱不存在,2:今日已重置,3:重置失败
    """
    if email_check(email):
        return 1

    if email_is_reset(email):
        return 2

    password = gen_random_str(8)

    try:
        database.connect()
        cursor.execute(f'update {user_data} set password = "{password}", reset_time = "{str(get_timestamp())}" where uemail = "{email}";')
        database.commit()
    except Exception as e:
        print(e)
        return 3

    send_reset_mail(receiver=email, password=password)

    return 0


def email_is_reset(email: str) -> bool:
    database.connect()
    cursor.execute(f'SELECT reset_time FROM {user_data} WHERE uemail = "{email}";')
    data_ = cursor.fetchall()
    if data_[0][0] == str(get_timestamp()):
        return True
    return False


def get_user_lnh(email: str):
    """
    获取用户权限
    :param email: 用户邮箱
    :return: 0:超级管理员,1:管理员,2:用户,3:游客
    """
    database.connect()
    cursor.execute(f'SELECT level, uname, headurl FROM {user_data} WHERE uemail = "{email}";')
    data_ = cursor.fetchall()
    return data_[0][0], data_[0][1], data_[0][2]


def get_user_cookie(email: str):
    """
    获取用户cookie
    :param email: 用户邮箱
    :return: 字符串(如果没有cookie则返回None)
    """
    database.connect()
    cursor.execute(f'SELECT cookie FROM {user_data} WHERE uemail = "{email}"')
    data = cursor.fetchall()
    try:
        return data[0][0]
    except IndexError:
        return None


def get_user_list(index: int = 0, end: int = 100, access: int = 1):
    """
    获取制定uid范围的用户信息
    :param access: 权限，1:管理员;0:超级管理员
    :param index: 起始uid(包含)
    :param end: 结束uid(包含)
    :return: list
    :example:[{'uid': 1, 'email': 'kawaiiorv@gmail.com', 'name': '枝江最甜小草莓', 'password': '******'}]
    """
    database.connect()
    if access == 0:
        cursor.execute(f'SELECT uid, uemail, uname, password FROM {user_data} WHERE uid BETWEEN {index} AND {end} AND level != 0')
        data_ = cursor.fetchall()
    else:
        cursor.execute(f'SELECT uid, uemail, uname, password FROM {user_data} WHERE uid BETWEEN {index} AND {end} AND level = 2')
        data_ = cursor.fetchall()

    _data_ = []

    for i in data_:
        _data_.append(
            {
                "uid": i[0],
                "email": i[1],
                "name": i[2],
                "password": i[3]
            }
        )

    return _data_


def email_check(email: str) -> bool:
    """
    检查该邮箱是否已被注册
    :param email: 邮箱
    :return: boolean
    """
    database.connect()
    cursor.execute(f'SELECT * FROM {user_data} WHERE uemail = "{email}"')
    data_ = cursor.fetchall()

    if not data_:
        return True
    return False


def use_icode(icode: str):
    """
    使用邀请码（令邀请码失效）
    :param icode: 邀请码
    :return: 无
    """
    database.connect()
    cursor.execute(f'update {code_data} set active = 0 where icode = "{icode}";')
    database.commit()


def icode_check(icode: str) -> bool:
    """
    检测icode是否可用
    :param icode: 邀请码
    :return: boolean
    """
    database.connect()
    cursor.execute(f'SELECT active FROM {code_data} WHERE icode = "{icode}"')
    data = cursor.fetchall()

    if not data:
        return False

    try:
        if data[0][0] == 1:
            return True
    except IndexError:
        return False
    return False


def gen_icode(num: int):
    """
    生成邀请码
    :param num: 生成的数量
    :return: 无
    """
    sql = f'insert into {code_data} (icode) value'

    for i in range(num):
        sql += f'("{gen_random_str(16, only_capital=True)}"),'

    sql = sql[:-1]
    sql += ';'

    database.connect()
    cursor.execute(sql)
    database.commit()


def get_icode():
    """
    获取所有可以使用的icode
    :return: list
    :example: ['093a3Xag0bHLfz8q', 'xKfn9oClWHALRz3P', 'Sz2XbkrSEiO3dBcu']
    """
    database.connect()
    cursor.execute(f'SELECT icode FROM {code_data} WHERE active = 1')
    data_ = cursor.fetchall()
    return format_sql_list(data_)


def format_sql_list(icode_list: list):
    new_list = []
    for i in icode_list:
        new_list.append(i[0])
    return new_list


if __name__ == '__main__':
    # print(email_check('kawaiiorv@gmail.com'))
    # gen_icode(10)
    # use_icode('cu8Of3nki3alvr8l')
    # print(icode_check('cu8Of3nki3alvr8l'))
    # level = get_user_cookie('kawa000iiorv@gmail.com')
    # print(level)
    # print(type(level))

    ...

